package com.qdlc.p2p.manage.action;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.springframework.beans.factory.annotation.Qualifier;

import com.opensymphony.xwork2.ModelDriven;
import com.qd.p2p.adapter.AdaptedRequestHandleService;
import com.qd.p2p.adapter.param.QueryTotalBalanceParameter;
import com.qd.p2p.adapter.response.QueryTotalBalanceResponse;
import com.qd.p2p.sina.pay.enums.AccountType;
import com.qd.p2p.sina.pay.enums.IdentityType;
import com.qd.p2p.sina.pay.response.sinaQueryBalanceResponse;
import com.qd.p2p.sina.service.SinaPayService;
import com.qdlc.p2p.biz.service.AccountRechargeService;
import com.qdlc.p2p.biz.service.CollectPayService;
import com.qdlc.p2p.biz.service.TppMerchantLogService;
import com.qdlc.p2p.biz.service.TppTradeService;
import com.qdlc.p2p.biz.service.UserService;
import com.qdlc.p2p.biz.tpp.model.SinaCollectTrade;
import com.qdlc.p2p.biz.web.action.BaseAction;
import com.qdlc.p2p.common.constant.Constant;
import com.qdlc.p2p.common.constant.SinaConstant;
import com.qdlc.p2p.common.core.ReturnResult;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.common.util.OrderNoUtils;
import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.dal.common.SystemConfigHelper;
import com.qdlc.p2p.dal.common.SystemConfigHelper.Nid;
import com.qdlc.p2p.dal.common.model.jpa.PageDataList;
import com.qdlc.p2p.dal.dto.TppMerchantLog;
import com.qdlc.p2p.dal.dto.TppTradeLog;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.model.TppMerchantLogModel;
import com.qdlc.p2p.dal.model.TppModel;
import com.qdlc.p2p.dal.util.UserUtils;

/**
 * 新浪第三方商户平台操作
 *
 * @author ygw
 * @version 2.0
 * @date 2016年1月14日 上午9:28:36
 */
public class ManageTppSinaMerchantLogAction extends BaseAction<TppMerchantLogModel> implements ModelDriven<TppMerchantLogModel> {
	
	private static Logger logger = Logger.getLogger(ManageTppSinaMerchantLogAction.class);
	
	@Resource
	private TppMerchantLogService tppMerchantLogService;
	@Resource
	private UserService userService;
	@Resource
	private AccountRechargeService accountRechargeService;
	@Resource
	private TppTradeService tppTradeService;
	@Resource
	private SinaPayService sinaPayService;
    @Resource
    @Qualifier("transferAccountsService")
    private CollectPayService collectService;
    @Resource
    protected AdaptedRequestHandleService paySerivce;
	
	private Map<String, Object> data;
	
	/**
	 * 第三方商户平台操作管理界面
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action("/modules/tpp/tppMerchantLog/" + Constant.TPP_PACKAGE + "/tppMerchantLogManager")
	public String tppMerchantLogManager() throws Exception {
		
		return "tppMerchantLogManager";
	}
	
	/**
	 * 第三方商户平台操作记录
	 * 
	 * @throws Exception
	 */
	@Action("/modules/tpp/tppMerchantLog/" + Constant.TPP_PACKAGE + "/tppMerchantLogList")
	public void tppMerchantLogList() throws Exception {
		String status = paramString("status");
		if (StringUtil.isBlank(status)) {
			model.setStatus((byte) 99);
		}
		String type = paramString("type");
		if (StringUtil.isBlank(type)) {
			model.setType((byte) 99);
		}
		PageDataList<TppMerchantLogModel> pageList = tppMerchantLogService.list(model);
		int totalPage = pageList.getPage().getTotal();
		data = new HashMap<String, Object>();
		data.put("total", totalPage);
		data.put("rows", pageList.getList());
		printJson(getStringOfJpaObj(data));
	}
	
	/**
	 * 第三方商户给用户转账页面
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action("/modules/tpp/tppMerchantLog/" + Constant.TPP_PACKAGE + "/tppTransferPage")
	public String tppTransferPage() throws Exception {
		// 查询商户余额
		if ("baofoo".equals(SystemConfigHelper.getSystemConfig(Nid.TPP_NAME).getValue())) {// 宝付
			QueryTotalBalanceParameter parameter = new QueryTotalBalanceParameter();
			parameter.setCurrentDate(DateUtil.dateStr7(DateUtil.getNow()));
			QueryTotalBalanceResponse response = paySerivce.queryTotalBalance(parameter);
			request.setAttribute("userMoney", response.getBalance());
		} else {// 新浪
			String tppId = SystemConfigHelper.getValue(SystemConfigHelper.Nid.MERCHANT_ID); // 平台帐号
			sinaQueryBalanceResponse response=sinaPayService.queryBalance(tppId, IdentityType.MEMBER_ID, AccountType.BASIC);
			request.setAttribute("totalMoney", response.getAvailableBalance());
			request.setAttribute("userMoney", response.getAvailableBalance());
		}
		request.setAttribute("web_name", SystemConfigHelper.getValue(SystemConfigHelper.Nid.WEB_NAME));
		return "tppTransferPage";
	}

	/**
	 * 用户给第三方商户转账页面
	 *
	 * @return
	 * @throws Exception
	 */
	@Action("/modules/tpp/tppMerchantLog/" + Constant.TPP_PACKAGE + "/tppTransferToWebPage")
	public String tppTransferToWebPage() throws Exception {
		// 查询商户余额
		if ("baofoo".equals(SystemConfigHelper.getSystemConfig(Nid.TPP_NAME).getValue())) {// 宝付
			QueryTotalBalanceParameter parameter = new QueryTotalBalanceParameter();
			parameter.setCurrentDate(DateUtil.dateStr7(DateUtil.getNow()));
			QueryTotalBalanceResponse response = paySerivce.queryTotalBalance(parameter);
			request.setAttribute("userMoney", response.getBalance());
		} else {// 新浪
			String tppId = SystemConfigHelper.getValue(SystemConfigHelper.Nid.MERCHANT_ID); // 平台帐号
			sinaQueryBalanceResponse response=sinaPayService.queryBalance(tppId, IdentityType.MEMBER_ID, AccountType.BASIC);
			request.setAttribute("totalMoney", response.getAvailableBalance());
			request.setAttribute("userMoney", response.getAvailableBalance());
		}
		request.setAttribute("web_name", SystemConfigHelper.getValue(SystemConfigHelper.Nid.WEB_NAME));
		return "tppTransferToWebPage";
	}

	/**
	 * 第三方商户给用户转账
	 *
	 * @throws Exception
	 */
	@Action("/modules/tpp/tppMerchantLog/" + Constant.TPP_PACKAGE + "/tppTransfer")
	public void tppTransfer() throws Exception {
		User user = userService.getUserByUserName(paramString("userName"));
		model.validUser(user);
		model.setToAccount(user.getUserName());
		model.validTransfer();

		byte status = TppMerchantLogModel.STATUS_UNTREATED;
		String msg = "";
		String ordId = OrderNoUtils.getSerialNumber();
		if ("baofoo".equals(SystemConfigHelper.getSystemConfig(Nid.TPP_NAME).getValue())) {// 宝付
			String tppId = SystemConfigHelper.getValue(SystemConfigHelper.Nid.MERCHANT_ID); // 平台商户号

			msg = "操作成功";
			status = TppMerchantLogModel.STATUS_SUCEESS;
			double transAmt = model.getMoney();// 转账金额
			// 执行转账业务（商户账户代收到新浪中间账户代付到客户账户）
			TppTradeLog tppTradeLog = new TppTradeLog(tppId, user.getTppUserCustId(), SinaConstant.IDENTITY_TYPE_EMAIL, transAmt,
					ordId, SinaConstant.TRADE_STATUS_WAIT_PAY, SinaConstant.TRADE_CODE_1001, SinaConstant.TRANSFER, SinaConstant.TRANSFER_TO_USER+"");
			ReturnResult returnResult = collectService.requestOrder(tppTradeLog);
			if(returnResult.isSuccess()) {
				if (model.getIsAccountLog() == 1) {// 是否需要生成资金记录
					// 保存用户充值记录
					accountRechargeService.systemRecharge(ordId, transAmt, user, getOperator());
				}
			} else {
				status = TppMerchantLogModel.STATUS_FAIL;
				msg = "接口请求失败";
			}
		} else {//新浪
			String tppId = SystemConfigHelper.getValue(SystemConfigHelper.Nid.MEMBER_EMAIL); // 平台Email

			msg = "操作成功";
			status = TppMerchantLogModel.STATUS_SUCEESS;
			double transAmt = model.getMoney();// 转账金额
			// 执行转账业务（商户账户代收到新浪中间账户代付到客户账户）
			TppTradeLog tppTradeLog = new TppTradeLog(tppId, user.getTppUserCustId(), SinaConstant.IDENTITY_TYPE_EMAIL, transAmt,
					ordId, SinaConstant.TRADE_STATUS_WAIT_PAY, SinaConstant.TRADE_CODE_1001, SinaConstant.TRANSFER, "");
			SinaCollectTrade collTrade = tppTradeService.collTrade(tppTradeLog, TppModel.TRANSFER);
			if(collTrade != null && !(SinaConstant.TRADE_STATUS_FAILED.equals(collTrade.getTrade_status()))) {
				if (model.getIsAccountLog() == 1) {// 是否需要生成资金记录
					// 保存用户充值记录
					accountRechargeService.systemRecharge(ordId, transAmt, user, getOperator());
				}
			} else {
				status = TppMerchantLogModel.STATUS_FAIL;
				msg = collTrade.getResponse_message();
			}
		}
		
		// 保存平台操作记录
		TppMerchantLog merchantLog = new TppMerchantLog(getOperator(), model.getAccount(), user.getUserName(), model.getMoney(), 0,
				status, TppMerchantLogModel.TYPE_TRANSFER, ordId, msg);
		tppMerchantLogService.save(merchantLog);
		printWebSuccess();
	}

	/**
	 * 用户给第三方商户转账
	 *
	 * @throws Exception
	 */
	@Action("/modules/tpp/tppMerchantLog/" + Constant.TPP_PACKAGE + "/tppTransferToWeb")
	public void tppTransferToWeb() throws Exception {
		User user = userService.getUserByUserName(paramString("userName"));
		model.validUser(user);
		model.setToAccount(user.getUserName());
		model.validTransfer();

		String ordId = OrderNoUtils.getSerialNumber();
		String tppId = SystemConfigHelper.getValue(SystemConfigHelper.Nid.MERCHANT_ID); // 平台帐号

		String msg = "操作成功";
		byte status = TppMerchantLogModel.STATUS_SUCEESS;
		double transAmt = model.getMoney();// 转账金额
		// 执行转账业务（用户账户代收到新浪中间账户代付到平台账户）
		TppTradeLog tppTradeLog = new TppTradeLog(UserUtils.getUserTppCustId(user.getUserId()), tppId, SinaConstant.IDENTITY_TYPE_UID, transAmt,
				ordId, SinaConstant.TRADE_STATUS_WAIT_PAY, SinaConstant.TRADE_CODE_1001, SinaConstant.TRANSFER, SinaConstant.TRANSFER_TO_MERCHANT+"");
		if ("baofoo".equals(SystemConfigHelper.getSystemConfig(Nid.TPP_NAME).getValue())) {// 宝付
			ReturnResult returnResult = collectService.requestOrder(tppTradeLog);
			if(returnResult.isSuccess()) {

			} else {
				status = TppMerchantLogModel.STATUS_FAIL;
				msg = "接口请求失败";
			}
		} else {// 新浪
			SinaCollectTrade collTrade = tppTradeService.collTrade(tppTradeLog,TppModel.TRANSFER);
			if(collTrade != null && !(SinaConstant.TRADE_STATUS_FAILED.equals(collTrade.getTrade_status()))) {

			} else {
				status = TppMerchantLogModel.STATUS_FAIL;
				msg = collTrade.getResponse_message();
			}
		}
		
		// 保存平台操作记录
		TppMerchantLog merchantLog = new TppMerchantLog(getOperator(), user.getUserName(), model.getAccount(), model.getMoney(), 0,
				status, TppMerchantLogModel.TYPE_TRANSFER, ordId, msg);
		tppMerchantLogService.save(merchantLog);
		printWebSuccess();
	}
}